package com.unreal.resourcemanager.controller;

import com.unreal.resourcemanager.pojo.ResourceVo;
import com.unreal.resourcemanager.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @Author: unreal
 * @Date: 2021-03-20 15:28
 * @Description:
 */
@Controller
public class mainController {
    @Autowired
    ManagerService managerService;

    @RequestMapping("/")
    public String index(Model model){
        String currentPath = "/";
        List<ResourceVo> list = managerService.loadFiles(currentPath);
        if(list != null && list.size() != 0){
            currentPath = list.get(0).getParentFilePath();
        }
        model.addAttribute("currentPath",currentPath);
        model.addAttribute("nodes",list);
        return "index";
    }

    @RequestMapping("/loadFiles")
    @ResponseBody
    public List<ResourceVo> loadFiles(Model model,String filePath){
        List<ResourceVo> list = managerService.loadFiles(filePath);
        return list;
    }

    @RequestMapping("/download")
    public void loadFiles(HttpServletResponse response, String url){
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            //清空下载文件的空白行（空白行是因为有的前端代码编译后产生的）
            response.reset();
            String fileName = url.substring(url.lastIndexOf("/")+1,url.length());
            //设置响应头，把文件名字设置好
            response.setHeader("Content-Disposition", "attachment; filename="+fileName);
            //解决编码问题
            response.setContentType("application/octet-stream; charset=utf-8");
            FileInputStream fis = new FileInputStream(new File(url));
            //输出流开始写出文件（FileUtils是Apache下的工具类可以直接调用）
            byte[] data = new byte[1024];
            while (fis.read(data)!= -1){
                os.write(data);
            }
            //刷新流
            os.flush();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
